"""
图表生成工具模块
提供多种图表类型的生成功能，支持百分比数据
"""

import json
from datetime import datetime
from typing import List, Dict, Any, Union, Optional
from enum import Enum


class ChartType(Enum):
    """图表类型枚举"""
    BAR = "bar"
    LINE = "line"
    PIE = "pie"
    SCATTER = "scatter"


class ChartGenerator:
    """图表生成器类 - 支持百分比数据"""

    @staticmethod
    def generate_chart_options(
            data: List[Dict[str, Any]],
            chart_type: Optional[ChartType] = None,
            title: str = "数据可视化图表"
    ) -> Dict[str, Any]:
        """
        根据数据和图表类型生成ECharts配置选项

        Args:
            data: 数据列表
            chart_type: 图表类型
            title: 图表标题

        Returns:
            ECharts配置选项字典
        """
        if not data:
            return {}

        # 根据数据特征自动选择合适的图表类型
        if chart_type is None:
            chart_type = ChartGenerator._auto_detect_chart_type(data)

        # 生成对应类型的图表配置
        if chart_type == ChartType.BAR:
            return ChartGenerator._generate_bar_chart_options(data, title)
        elif chart_type == ChartType.LINE:
            return ChartGenerator._generate_line_chart_options(data, title)
        elif chart_type == ChartType.PIE:
            return ChartGenerator._generate_pie_chart_options(data, title)
        elif chart_type == ChartType.SCATTER:
            return ChartGenerator._generate_scatter_chart_options(data, title)
        else:
            return ChartGenerator._generate_bar_chart_options(data, title)

    @staticmethod
    def _is_numeric_value(value: Any) -> bool:
        """判断值是否为数值类型，包括百分比字符串"""
        if isinstance(value, (int, float)):
            return True
        elif isinstance(value, str):
            # 检查是否为百分比字符串，如 "5.7%", "10%" 等
            if value.endswith('%'):
                try:
                    float(value.strip('%')) / 100
                    return True
                except ValueError:
                    return False
            # 检查是否为普通数字字符串
            try:
                float(value)
                return True
            except ValueError:
                return False
        return False

    @staticmethod
    def _convert_to_float(value: Any) -> float:
        """将值转换为浮点数，处理百分比"""
        if isinstance(value, (int, float)):
            # 对于数值类型，直接返回并处理精度
            return float(value)
        elif isinstance(value, str):
            if value.endswith('%'):
                try:
                    # 对于百分比字符串，先转换再处理精度
                    percent_value = float(value.strip('%'))
                    return percent_value / 100
                except ValueError:
                    return 0.0
            else:
                try:
                    # 对于普通数字字符串，转换后处理精度
                    num_value = float(value)
                    return num_value
                except ValueError:
                    return 0.0
        else:
            try:
                return float(value)
            except (ValueError, TypeError):
                return 0.0

    @staticmethod
    def _is_percentage_field(field_name: str, data: List[Dict[str, Any]]) -> bool:
        """判断字段是否为百分比类型"""
        # 通过字段名判断
        if any(keyword in field_name for keyword in ['率', '收益率', '比例', '占比', '百分比']):
            return True

        # 通过数据内容判断（如果前几个值都是百分比格式）
        if data and field_name in data[0]:
            sample_values = [row[field_name] for row in data[:3] if field_name in row]
            if sample_values:
                percentage_count = sum(1 for val in sample_values if isinstance(val, str) and val.endswith('%'))
                return percentage_count == len(sample_values)  # 所有样本都是百分比格式

        return False

    @staticmethod
    def _get_percentage_fields(data: List[Dict[str, Any]]) -> List[str]:
        """获取所有百分比字段"""
        if not data:
            return []

        percentage_fields = []
        for field in data[0].keys():
            if ChartGenerator._is_percentage_field(field, data):
                percentage_fields.append(field)
        return percentage_fields

    @staticmethod
    def _auto_detect_chart_type(data: List[Dict[str, Any]]) -> ChartType:
        """
        根据数据特征自动检测合适的图表类型

        Args:
            data: 数据列表

        Returns:
            推荐的图表类型
        """
        if not data:
            return ChartType.BAR

        # 检查数据特征
        first_row = data[0]
        numeric_fields = [k for k, v in first_row.items() if ChartGenerator._is_numeric_value(v)]
        categorical_fields = [k for k, v in first_row.items() if
                              isinstance(v, str) and not ChartGenerator._is_numeric_value(v)]

        # 如果数据量很大，优先考虑适合大数据量的图表类型
        data_size = len(data)
        
        # 对于大量数据，使用折线图或散点图
        if data_size > 100:
            # 如果有时间序列字段，使用折线图
            time_fields = [k for k, v in first_row.items() if "date" in k.lower() or "time" in k.lower()]
            if time_fields:
                return ChartType.LINE
            # 否则使用散点图
            elif len(numeric_fields) >= 2:
                return ChartType.SCATTER
            else:
                return ChartType.LINE
        # 中等数据量(10-100)，使用柱状图
        elif data_size > 10:
            return ChartType.BAR
        # 小数据量(<=10)，根据字段情况选择
        else:
            # 如果有一个分类字段和一个数值字段，使用饼图
            if len(categorical_fields) == 1 and len(numeric_fields) == 1:
                return ChartType.PIE
            # 如果有多个数值字段，使用柱状图
            elif len(numeric_fields) > 1:
                return ChartType.BAR
            # 默认使用柱状图
            else:
                return ChartType.BAR

    @staticmethod
    def _generate_bar_chart_options(data: List[Dict[str, Any]], title: str) -> Dict[str, Any]:
        """生成柱状图配置 - 支持百分比数据"""
        if not data:
            return {}

        first_row = data[0]
        # 使用新的数值判断方法
        numeric_fields = [k for k, v in first_row.items() if ChartGenerator._is_numeric_value(v)]
        categorical_fields = [k for k, v in first_row.items() if
                              isinstance(v, str) and not ChartGenerator._is_numeric_value(v)]
        percentage_fields = ChartGenerator._get_percentage_fields(data)

        # 如果没有分类字段，使用行索引作为x轴
        if not categorical_fields:
            x_data = [str(i) for i in range(len(data))]
            x_field = "索引"
        else:
            x_data = [row.get(categorical_fields[0], f"项目{i}") for i, row in enumerate(data)]
            x_field = categorical_fields[0]

        # 生成系列数据
        series = []
        for field in numeric_fields[:5]:  # 限制最多5个数值字段
            # 使用新的转换方法
            series_data = [ChartGenerator._convert_to_float(row.get(field, 0)) for row in data]
            is_percentage = field in percentage_fields

            series_config = {
                "name": field,
                "type": "bar",
                "data": series_data,
                "itemStyle": {
                    "color": ChartGenerator._get_series_color(len(series))
                }
            }

            # 如果是百分比字段，添加标签格式化
            if is_percentage:
                series_config["label"] = {
                    "show": True,
                    "position": "top",
                    "formatter": "{@[1]\\.2%}"
                }

            series.append(series_config)

        # 设置Y轴配置 - 只有当所有字段都是百分比时才显示百分比格式
        all_fields_percentage = all(field in percentage_fields for field in numeric_fields[:5])

        y_axis_config = {
            "type": "value"
        }

        if all_fields_percentage and numeric_fields[:5]:
            y_axis_config["axisLabel"] = {  # type: ignore
                "formatter": "{value:.2%}"
            }  # type: ignore

        return {
            "title": {
                "text": title
            },
            "tooltip": {
                "trigger": "axis",
                "valueFormatter": ChartGenerator._get_value_formatter(percentage_fields)
            },
            "legend": {
                "data": numeric_fields[:5]
            },
            "xAxis": {
                "type": "category",
                "data": x_data,
                "name": x_field
            },
            "yAxis": y_axis_config,
            "series": series
        }

    @staticmethod
    def _generate_line_chart_options(data: List[Dict[str, Any]], title: str) -> Dict[str, Any]:
        """生成折线图配置 - 支持百分比数据"""
        if not data:
            return {}

        first_row = data[0]
        numeric_fields = [k for k, v in first_row.items() if ChartGenerator._is_numeric_value(v)]
        time_fields = [k for k, v in first_row.items() if "date" in k.lower() or "time" in k.lower()]
        percentage_fields = ChartGenerator._get_percentage_fields(data)

        # 如果有时间字段，使用时间作为x轴
        if time_fields:
            x_data = [row.get(time_fields[0], f"时间{i}") for i, row in enumerate(data)]
            x_field = time_fields[0]
        else:
            x_data = [str(i) for i in range(len(data))]
            x_field = "时间"

        # 生成系列数据
        series = []
        for field in numeric_fields[:5]:  # 限制最多5个数值字段
            series_data = [ChartGenerator._convert_to_float(row.get(field, 0)) for row in data]
            is_percentage = field in percentage_fields

            series_config = {
                "name": field,
                "type": "line",
                "data": series_data,
                "smooth": True,
                "itemStyle": {
                    "color": ChartGenerator._get_series_color(len(series))
                }
            }

            # 如果是百分比字段，添加标签格式化
            if is_percentage:
                series_config["label"] = {
                    "show": True,
                    "formatter": "{@[1]\\.2%}"
                }

            series.append(series_config)

        # 设置Y轴配置
        all_fields_percentage = all(field in percentage_fields for field in numeric_fields[:5])

        y_axis_config = {
            "type": "value"
        }

        if all_fields_percentage and numeric_fields[:5]:
            y_axis_config["axisLabel"] = {  # type: ignore
                "formatter": "{value:.2%}"
            }  # type: ignore

        return {
            "title": {
                "text": title
            },
            "tooltip": {
                "trigger": "axis",
                "valueFormatter": ChartGenerator._get_value_formatter(percentage_fields)
            },
            "legend": {
                "data": numeric_fields[:5]
            },
            "xAxis": {
                "type": "category",
                "data": x_data,
                "name": x_field
            },
            "yAxis": y_axis_config,
            "series": series
        }

    @staticmethod
    def _generate_pie_chart_options(data: List[Dict[str, Any]], title: str) -> Dict[str, Any]:
        """生成饼图配置 - 支持百分比数据"""
        if not data or len(data) == 0:
            return {}

        first_row = data[0]
        numeric_fields = [k for k, v in first_row.items() if ChartGenerator._is_numeric_value(v)]
        categorical_fields = [k for k, v in first_row.items() if
                              isinstance(v, str) and not ChartGenerator._is_numeric_value(v)]
        percentage_fields = ChartGenerator._get_percentage_fields(data)

        if not numeric_fields or not categorical_fields:
            return {}

        # 取第一个数值字段和第一个分类字段
        value_field = numeric_fields[0]
        category_field = categorical_fields[0]
        is_percentage = value_field in percentage_fields

        # 处理大数据量的情况，对饼图数据进行聚合
        pie_data = []
        data_size = len(data)
        
        # 如果数据量超过15条，进行聚合处理
        if data_size > 15:
            # 统计各个分类的总和或平均值
            category_stats = {}
            for row in data:
                category = str(row.get(category_field, "未知"))
                value = ChartGenerator._convert_to_float(row.get(value_field, 0))
                
                if category in category_stats:
                    category_stats[category]["sum"] += value
                    category_stats[category]["count"] += 1
                else:
                    category_stats[category] = {"sum": value, "count": 1}
            
            # 计算平均值并排序，取前15个
            aggregated_data = [
                (category, stats["sum"] / stats["count"] if stats["count"] > 0 else 0)
                for category, stats in category_stats.items()
            ]
            aggregated_data.sort(key=lambda x: x[1], reverse=True)
            
            # 取前10个分类，其他合并为"其他"
            top_categories = aggregated_data[:10]
            other_sum = sum([value for _, value in aggregated_data[10:]])
            
            for category, value in top_categories:
                pie_data.append({
                    "name": category,
                    "value": value
                })
            
            # 添加"其他"类别（如果有）
            if other_sum > 0:
                pie_data.append({
                    "name": "其他",
                    "value": other_sum
                })
        else:
            # 数据量较小时，正常处理
            for row in data:
                value = ChartGenerator._convert_to_float(row.get(value_field, 0))
                pie_data.append({
                    "name": str(row.get(category_field, "未知")),
                    "value": value
                })

        # 设置标签格式化
        label_formatter = '{b}: {c} ({d}%)'
        tooltip_formatter = '{a} <br/>{b}: {c} ({d}%)'

        if is_percentage:
            label_formatter = '{b}: {c:.2%} ({d}%)'
            tooltip_formatter = '{a} <br/>{b}: {c:.2%} ({d}%)'

        return {
            "title": {
                "text": title
            },
            "tooltip": {
                "trigger": "item",
                "formatter": tooltip_formatter
            },
            "legend": {
                "orient": "vertical",
                "left": "left"
            },
            "series": [
                {
                    "name": value_field,
                    "type": "pie",
                    "radius": "50%",
                    "data": pie_data,
                    "emphasis": {
                        "itemStyle": {
                            "shadowBlur": 10,
                            "shadowOffsetX": 0,
                            "shadowColor": "rgba(0, 0, 0, 0.5)"
                        }
                    },
                    "label": {
                        "formatter": label_formatter
                    }
                }
            ]
        }

    @staticmethod
    def _generate_scatter_chart_options(data: List[Dict[str, Any]], title: str) -> Dict[str, Any]:
        """生成散点图配置 - 支持百分比数据"""
        if not data or len(data) < 2:
            return {}

        first_row = data[0]
        numeric_fields = [k for k, v in first_row.items() if ChartGenerator._is_numeric_value(v)]
        percentage_fields = ChartGenerator._get_percentage_fields(data)

        if len(numeric_fields) < 2:
            return {}

        # 取前两个数值字段作为x轴和y轴
        x_field = numeric_fields[0]
        y_field = numeric_fields[1]
        x_is_percentage = x_field in percentage_fields
        y_is_percentage = y_field in percentage_fields

        # 处理大数据量的情况，对散点图数据进行采样
        scatter_data = []
        data_size = len(data)
        
        # 如果数据量超过1000条，进行采样处理
        if data_size > 1000:
            # 每隔一定间隔取一个点
            step = data_size // 500  # 最多显示500个点
            step = max(1, step)  # 确保步长至少为1
            
            for i in range(0, data_size, step):
                row = data[i]
                x_value = ChartGenerator._convert_to_float(row.get(x_field, 0))
                y_value = ChartGenerator._convert_to_float(row.get(y_field, 0))
                scatter_data.append([x_value, y_value])
        else:
            # 数据量较小时，正常处理
            for row in data:
                x_value = ChartGenerator._convert_to_float(row.get(x_field, 0))
                y_value = ChartGenerator._convert_to_float(row.get(y_field, 0))
                scatter_data.append([x_value, y_value])

        # 设置坐标轴配置
        x_axis_config = {
            "type": "value",
            "name": x_field
        }

        y_axis_config = {
            "type": "value",
            "name": y_field
        }

        if x_is_percentage:
            x_axis_config["axisLabel"] = {"formatter": "{value:.2%}"}  # type: ignore

        if y_is_percentage:
            y_axis_config["axisLabel"] = {"formatter": "{value:.2%}"}  # type: ignore

        # 设置tooltip格式化
        tooltip_formatter = [
            f'{x_field}: ' + ('{c0:.2%}' if x_is_percentage else '{c0}'),
            f'{y_field}: ' + ('{c1:.2%}' if y_is_percentage else '{c1}')
        ]

        return {
            "title": {
                "text": title
            },
            "tooltip": {
                "trigger": "item",
                "formatter": lambda
                    params: f"{params.seriesName}<br/>{tooltip_formatter[0]}<br/>{tooltip_formatter[1]}".format(
                    c0=params.value[0], c1=params.value[1]
                )
            },
            "xAxis": x_axis_config,
            "yAxis": y_axis_config,
            "series": [{
                "name": f"{x_field} vs {y_field}",
                "type": "scatter",
                "data": scatter_data,
                "itemStyle": {
                    "color": ChartGenerator._get_series_color(0)
                }
            }]
        }

    @staticmethod
    def _get_value_formatter(percentage_fields: List[str]) -> Any:  # type: ignore
        """生成值格式化器"""

        def formatter(value: float, series_name: str) -> str:
            if series_name in percentage_fields:
                # 对于百分比数据，尝试保持合理的精度
                # 先四舍五入到合适的精度，避免浮点数误差
                if abs(value) < 0.01:
                    rounded_value = round(value, 6)  # 对于小于1%的值，保留6位小数
                    return f"{rounded_value:.4%}"
                else:
                    rounded_value = round(value, 4)  # 对于大于等于1%的值，保留4位小数
                    return f"{rounded_value:.2%}"
            else:
                return str(value)

        return formatter

    @staticmethod
    def _get_series_color(index: int) -> str:
        """
        根据索引获取系列颜色

        Args:
            index: 系列索引

        Returns:
            颜色值
        """
        colors = [
            "#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de",
            "#3ba272", "#fc8452", "#9a60b4", "#ea7ccc"
        ]
        return colors[index % len(colors)]


# 便捷函数
def generate_chart(data: List[Dict[str, Any]], chart_type: Optional[ChartType] = None, title: str = "数据可视化图表") -> \
Dict[str, Any]:
    """
    生成图表配置的便捷函数

    Args:
        data: 数据列表
        chart_type: 图表类型
        title: 图表标题

    Returns:
        ECharts配置选项字典
    """
    return ChartGenerator.generate_chart_options(data, chart_type, title)


def generate_html_content(data: List[Dict[str, Any]], title: str, description: str) -> str:
    """生成HTML内容"""
    # 将数据转换为HTML表格
    if not data:
        table_html = "<p>没有数据可显示</p>"
    else:
        # 生成表头
        headers = list(data[0].keys())
        header_html = "".join([f"<th class='px-4 py-2'>{header}</th>" for header in headers])

        # 生成表格行
        rows_html = ""
        for row in data:
            cells_html = "".join([f"<td class='border px-4 py-2'>{row.get(header, '')}</td>" for header in headers])
            rows_html += f"<tr>{cells_html}</tr>"

        table_html = f"""
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-300">
                <thead>
                    <tr class="bg-gray-100">
                        {header_html}
                    </tr>
                </thead>
                <tbody>
                    {rows_html}
                </tbody>
            </table>
        </div>
        """

    # 生成图表数据
    chart_options = generate_chart(data, title="数据可视化图表")

    # 获取百分比字段信息，用于JavaScript中的valueFormatter
    percentage_fields = []
    if data:
        # 这里调用你的百分比字段检测方法
        # 假设ChartGenerator类有这个静态方法
        percentage_fields = ChartGenerator._get_percentage_fields(data) if hasattr(ChartGenerator,
                                                                                   '_get_percentage_fields') else []

    # 清理不可JSON序列化的对象
    if "tooltip" in chart_options and "valueFormatter" in chart_options["tooltip"]:
        del chart_options["tooltip"]["valueFormatter"]

    # 清理系列数据中的formatter函数
    if "series" in chart_options:
        for series in chart_options["series"]:
            if "label" in series and "formatter" in series["label"]:
                series["label"]["formatter"] = "{value}"

    # 清理其他可能的函数对象
    def remove_functions(obj):
        if isinstance(obj, dict):
            keys_to_remove = []
            for key, value in obj.items():
                if callable(value):
                    keys_to_remove.append(key)
                elif isinstance(value, dict):
                    remove_functions(value)
                elif isinstance(value, list):
                    for item in value:
                        if isinstance(item, dict):
                            remove_functions(item)
            for key in keys_to_remove:
                del obj[key]
        elif isinstance(obj, list):
            for item in obj:
                if isinstance(item, dict):
                    remove_functions(item)

    remove_functions(chart_options)

    # 生成HTML模板
    html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <script src="https://unpkg.com/echarts@5.6.0/dist/echarts.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8f9fa;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 10px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }}
        .card {{
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            margin-bottom: 2rem;
        }}
        .chart-container {{
            height: 500px;  /* 增加高度确保图表显示 */
            width: 100%;
            margin: 2rem 0;
        }}
        .footer {{
            text-align: center;
            padding: 2rem;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
            margin-top: 2rem;
        }}
    </style>
</head>
<body>
    <div class="container">
        <header class="header">
            <h1 class="text-3xl font-bold mb-2">{title}</h1>
            <p class="text-xl opacity-90">{description}</p>
            <p class="mt-2 opacity-75">生成时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}</p>
        </header>

        <main>
            <section class="card">
                <h2 class="text-2xl font-semibold mb-4">数据概览</h2>
                <p class="mb-4">本报告基于 {len(data)} 条数据记录生成，以下是详细数据内容：</p>
                {table_html}
            </section>

            <section class="card">
                <h2 class="text-2xl font-semibold mb-4">数据可视化</h2>
                <div id="data-chart" class="chart-container"></div>
            </section>

            <section class="card">
                <h2 class="text-2xl font-semibold mb-4">分析摘要</h2>
                <div class="prose max-w-none">
                    <p>本报告展示了基金相关数据的可视化分析结果。通过图表和表格的形式，可以更直观地了解数据的分布和趋势。</p>
                    <p>主要发现：</p>
                    <ul class="list-disc pl-5 space-y-2">
                        <li>数据完整性：共分析 {len(data)} 条记录</li>
                        <li>数据字段：包含 {len(data[0]) if data else 0} 个字段</li>
                        <li>可视化展示：通过ECharts图表展示关键数据指标</li>
                    </ul>
                </div>
            </section>
        </main>

        <footer class="footer">
            <p>Created by Autobots</p>
            <p class="text-sm mt-1">页面内容均由 AI 生成，仅供参考</p>
        </footer>
    </div>

    <script>
        // 等待DOM加载完成
        document.addEventListener('DOMContentLoaded', function() {{
            // 图表配置
            const chartOptions = {json.dumps(chart_options, ensure_ascii=False, indent=2)};

            // 百分比字段列表
            const percentageFields = {json.dumps(percentage_fields, ensure_ascii=False)};

            // 重新创建valueFormatter函数
            if (chartOptions && chartOptions.tooltip) {{
                chartOptions.tooltip.valueFormatter = function (value, seriesName) {{
                    try {{
                        // 检查是否为百分比字段
                        if (percentageFields.includes(seriesName)) {{
                            // 对于百分比数据
                            if (Math.abs(value) < 0.01) {{
                                const roundedValue = Math.round(value * 1000000) / 1000000;
                                return (roundedValue * 100).toFixed(4) + '%';
                            }} else {{
                                const roundedValue = Math.round(value * 10000) / 10000;
                                return (roundedValue * 100).toFixed(2) + '%';
                            }}
                        }} else {{
                            // 对于非百分比字段
                            if (Number.isInteger(value)) {{
                                return value.toString();
                            }} else {{
                                const strValue = value.toString();
                                if (strValue.includes('.')) {{
                                    const decimalPart = strValue.split('.')[1];
                                    if (decimalPart.length > 6) {{
                                        return value.toFixed(6);
                                    }} else {{
                                        return strValue;
                                    }}
                                }} else {{
                                    return strValue;
                                }}
                            }}
                        }}
                    }} catch (e) {{
                        return value !== undefined ? value.toString() : '';
                    }}
                }};
            }}

            // 初始化图表
            const chartElement = document.getElementById('data-chart');
            if (chartElement && chartOptions && Object.keys(chartOptions).length > 0) {{
                const chart = echarts.init(chartElement);
                chart.setOption(chartOptions);

                // 窗口大小改变时重置图表大小
                window.addEventListener('resize', function() {{
                    chart.resize();
                }});
            }} else {{
                console.log("图表配置为空或图表容器未找到");
                if (chartElement) {{
                    chartElement.innerHTML = '<p class="text-center text-gray-500">暂无图表数据</p>';
                }}
            }}
        }});
    </script>
</body>
</html>"""

    return html_template.strip()

# def generate_html_content(data: List[Dict[str, Any]], title: str, description: str) -> str:
#     """生成HTML内容"""
#     # 将数据转换为HTML表格
#     if not data:
#         table_html = "<p>没有数据可显示</p>"
#     else:
#         # 生成表头
#         headers = list(data[0].keys())
#         header_html = "".join([f"<th class='px-4 py-2'>{header}</th>" for header in headers])
#
#         # 生成表格行
#         rows_html = ""
#         for row in data:
#             cells_html = "".join([f"<td class='border px-4 py-2'>{row.get(header, '')}</td>" for header in headers])
#             rows_html += f"<tr>{cells_html}</tr>"
#
#         table_html = f"""
#         <div class="overflow-x-auto">
#             <table class="min-w-full bg-white border border-gray-300">
#                 <thead>
#                     <tr class="bg-gray-100">
#                         {header_html}
#                     </tr>
#                 </thead>
#                 <tbody>
#                     {rows_html}
#                 </tbody>
#             </table>
#         </div>
#         """
#
#     # 生成图表数据
#     chart_options = generate_chart(data, title="数据可视化图表")
#
#     # 获取百分比字段信息，用于JavaScript中的valueFormatter
#     percentage_fields = []
#     if data:
#         percentage_fields = ChartGenerator._get_percentage_fields(data)
#
#     # 清理不可JSON序列化的对象
#     # 注意：我们不再删除valueFormatter，而是让它正确工作
#     # 但我们需要确保valueFormatter是可序列化的
#
#     # 如果有valueFormatter，我们需要特殊处理
#     if "tooltip" in chart_options and "valueFormatter" in chart_options["tooltip"]:
#         # 保存原始的valueFormatter函数
#         original_formatter = chart_options["tooltip"]["valueFormatter"]
#         # 删除它以避免序列化问题
#         del chart_options["tooltip"]["valueFormatter"]
#
#     # 清理系列数据中的formatter函数
#     if "series" in chart_options:
#         for series in chart_options["series"]:
#             if "label" in series and "formatter" in series["label"]:
#                 # 将函数替换为字符串格式
#                 series["label"]["formatter"] = "{value}"
#
#     # 清理其他可能的函数对象
#     def remove_functions(obj):
#         if isinstance(obj, dict):
#             keys_to_remove = []
#             for key, value in obj.items():
#                 # 特殊处理valueFormatter，保留它但确保它是可序列化的
#                 if callable(value) and key != "valueFormatter":
#                     keys_to_remove.append(key)
#                 elif isinstance(value, dict):
#                     remove_functions(value)
#                 elif isinstance(value, list):
#                     for item in value:
#                         if isinstance(item, dict):
#                             remove_functions(item)
#             for key in keys_to_remove:
#                 del obj[key]
#         elif isinstance(obj, list):
#             for item in obj:
#                 if isinstance(item, dict):
#                     remove_functions(item)
#
#     remove_functions(chart_options)
#
#     # 生成HTML模板
#     html_template = f"""
# <!DOCTYPE html>
# <html lang="zh-CN">
# <head>
#     <meta charset="UTF-8">
#     <meta name="viewport" content="width=device-width, initial-scale=1.0">
#     <title>{title}</title>
#     <script src="https://unpkg.com/echarts@5.6.0/dist/echarts.min.js"></script>
#     <script src="https://cdn.tailwindcss.com"></script>
#     <style>
#         body {{
#             font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
#             line-height: 1.6;
#             color: #333;
#             background-color: #f8f9fa;
#         }}
#         .container {{
#             max-width: 1200px;
#             margin: 0 auto;
#             padding: 20px;
#         }}
#         .header {{
#             background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
#             color: white;
#             padding: 2rem;
#             border-radius: 10px;
#             margin-bottom: 2rem;
#             box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
#         }}
#         .card {{
#             background: white;
#             border-radius: 10px;
#             box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
#             padding: 1.5rem;
#             margin-bottom: 2rem;
#         }}
#         .chart-container {{
#             height: 400px;
#             margin: 2rem 0;
#         }}
#         .footer {{
#             text-align: center;
#             padding: 2rem;
#             color: #6c757d;
#             border-top: 1px solid #dee2e6;
#             margin-top: 2rem;
#         }}
#     </style>
# </head>
# <body>
#     <div class="container">
#         <header class="header">
#             <h1 class="text-3xl font-bold mb-2">{title}</h1>
#             <p class="text-xl opacity-90">{description}</p>
#             <p class="mt-2 opacity-75">生成时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}</p>
#         </header>
#
#         <main>
#             <section class="card">
#                 <h2 class="text-2xl font-semibold mb-4">数据概览</h2>
#                 <p class="mb-4">本报告基于 {len(data)} 条数据记录生成，以下是详细数据内容：</p>
#                 {table_html}
#             </section>
#
#             <section class="card">
#                 <h2 class="text-2xl font-semibold mb-4">数据可视化</h2>
#                 <div id="data-chart" class="chart-container"></div>
#             </section>
#
#             <section class="card">
#                 <h2 class="text-2xl font-semibold mb-4">分析摘要</h2>
#                 <div class="prose max-w-none">
#                     <p>本报告展示了基金相关数据的可视化分析结果。通过图表和表格的形式，可以更直观地了解数据的分布和趋势。</p>
#                     <p>主要发现：</p>
#                     <ul class="list-disc pl-5 space-y-2">
#                         <li>数据完整性：共分析 {len(data)} 条记录</li>
#                         <li>数据字段：包含 {len(data[0]) if data else 0} 个字段</li>
#                         <li>可视化展示：通过ECharts图表展示关键数据指标</li>
#                     </ul>
#                 </div>
#             </section>
#         </main>
#
#         <footer class="footer">
#             <p>Created by Autobots</p>
#             <p class="text-sm mt-1">页面内容均由 AI 生成，仅供参考</p>
#         </footer>
#     </div>
#
#     <script>
#         // 图表配置
#         const chartOptions = {json.dumps(chart_options, ensure_ascii=False, indent=2)};
#
#         // 百分比字段列表
#         const percentageFields = {json.dumps(percentage_fields, ensure_ascii=False)};
#
#         // 重新创建valueFormatter函数
#         if (chartOptions.tooltip) {{
#             chartOptions.tooltip.valueFormatter = function (value, seriesName) {{
#                 // 这里实现与Python中_get_value_formatter相同的逻辑
#                 try {{
#                     // 检查是否为百分比字段
#                     if (percentageFields.includes(seriesName)) {{
#                         // 对于百分比数据，尝试保持合理的精度
#                         // 先四舍五入到合适的精度，避免浮点数误差
#                         if (Math.abs(value) < 0.01) {{
#                             const roundedValue = Math.round(value * 1000000) / 1000000;  // 保留6位小数
#                             return (roundedValue * 100).toFixed(4) + '%';
#                         }} else {{
#                             const roundedValue = Math.round(value * 10000) / 10000;  // 保留4位小数
#                             return (roundedValue * 100).toFixed(2) + '%';
#                         }}
#                     }} else {{
#                         // 对于非百分比字段，处理浮点数精度问题
#                         // 检查是否为整数
#                         if (Number.isInteger(value)) {{
#                             return value.toString();
#                         }} else {{
#                             // 对于小数，四舍五入到合适的小数位数
#                             // 检查小数部分的长度
#                             const strValue = value.toString();
#                             if (strValue.includes('.')) {{
#                                 const decimalPart = strValue.split('.')[1];
#                                 if (decimalPart.length > 6) {{
#                                     // 如果小数位数超过6位，四舍五入到6位
#                                     return value.toFixed(6);
#                                 }} else {{
#                                     return strValue;
#                                 }}
#                             }} else {{
#                                 return strValue;
#                             }}
#                         }}
#                     }}
#                 }} catch (e) {{
#                     // 如果出现任何错误，返回原始值
#                     return value.toString();
#                 }}
#             }};
#         }}
#
#         // 初始化图表
#         if (Object.keys(chartOptions).length > 0) {{
#             const chart = echarts.init(document.getElementById('data-chart'));
#             chart.setOption(chartOptions);
#
#             // 窗口大小改变时重置图表大小
#             window.addEventListener('resize', function() {{
#                 chart.resize();
#             }});
#         }} else {{
#             console.log("图表配置为空");
#             document.getElementById('data-chart').innerHTML = '<p class="text-center text-gray-500">暂无图表数据</p>';
#         }}
#     </script>
# </body>
# </html>
#     """
#
#     return html_template.strip()